package org.example.steamshop.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.transaction.Transactional;

import org.example.steamshop.model.CartItem;
import org.example.steamshop.model.Game;
import org.example.steamshop.model.Order;
import org.example.steamshop.repository.OrderRepository;
import org.example.steamshop.repository.UserRepository;
import org.example.steamshop.service.CartService;
import org.example.steamshop.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private CartService cartService;

    @Autowired
    private GameService gameService;

    public List<Order> getUserOrders(Long userId) {
        return orderRepository.findByUserId(userId);
    }

    @Transactional
    public Order createOrder(Long userId) {
        List<CartItem> cartItems = cartService.getCartItems(userId);
        if (cartItems.isEmpty()) {
            throw new RuntimeException("Cart is empty");
        }

        double totalAmount = cartItems.stream()
                .mapToDouble(item -> item.getGame().getPrice() * item.getQuantity())
                .sum();

        Order order = new Order();
        order.setUser(userRepository.findById(userId).orElse( null));
        order.setOrderDate(LocalDateTime.now());
        order.setTotalAmount(totalAmount);
        // 简化处理，实际应保存订单项到数据库
        Map<Game, Integer> items = new HashMap<>();
        for (CartItem item : cartItems) {
            items.put(item.getGame(), item.getQuantity());
        }
        order.setItems(items);
        Order savedOrder = orderRepository.save(order);

//         清空购物车
        cartService.clearCart(userId);

        return savedOrder;
    }

    @Transactional
    public boolean deleteOrder(Long orderId, Long userId) {
        // 直接检查订单是否属于用户
        if (!orderRepository.existsByIdAndUserId(orderId, userId)) {
            return false;
        }

        // 直接执行删除操作
        int deletedCount = orderRepository.deleteByOrderIdAndUserId(orderId, userId);
        return deletedCount > 0;
    }




}